package com.zbj.homemade.mybatis.proxy;

import com.zbj.homemade.mybatis.SqlSession;
import com.zbj.homemade.mybatis.conf.Configuration;
import com.zbj.homemade.mybatis.conf.MappedStatement;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @program: principle
 * @description:
 * @author: Yinn
 * @create: 2019-01-14 11:41
 **/
public class MapperProxy<T> implements InvocationHandler {

    /**
     * @Date 2019/1/14
     * @title 需要代理的mapper接口
     * @param
     * @return
     */
    private Class<T> mapperInterface;

    /**
     * @Date 2019/1/14
     * @title sql session
     * @param
     * @return
     */
    private SqlSession sqlSession;

    public MapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
        this.mapperInterface = mapperInterface;
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        String packageName = mapperInterface.getPackage().getName();

        String methodName = method.getName();

        String statement = packageName + "." + methodName;

        MappedStatement ms = sqlSession.getConfiguration().getMappedStatement(statement);

        switch (ms.getSqlCommandType()) {

            case INSERT:
                return sqlSession.insert(statement, args);

            case DELETE:
                return sqlSession.delete(statement, args);

            case UPDATE:
                return sqlSession.update(statement, args);

            case SELECT:
                return sqlSession.selectList(statement, args);

        }

        ///
        return null;

    }
}
